package com.yx.cloud.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.iot.base.service.req.DataParam;
import com.iot.base.service.req.DataBag;
import com.iot.common.utils.LogUtils;
import com.iot.product.sweeper.bean.FirmwareUpdateInfo;
import com.iot.product.sweeper.bean.RobotStatus;
import com.iot.product.sweeper.config.SweeperProductConfig;
import com.iot.sdk.yugong.resp.YuGongRespData;
import com.iot.sweeper.AppContext;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.databinding.FirmwareupgradeActivityBinding;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.utils.AppUtil;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.RomUtils;
import com.iot.product.sweeper.bean.Robot;
import com.iot.common.utils.Event;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.TimeEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * 创建时间 : 2018/12/26.
 * 创建人 :
 * 功能描述 :固件升级界面
 */
public class FirmwareUpgradeActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "FirmwareUpgradeActivity";
    private Dialog dialog, upgradeFailDialog;
    private boolean isCheck = false;
    private String mVersions = "", currentVersion;
    private int mProgress = 0;
    private Robot robot;
    private FirmwareupgradeActivityBinding binding;
    private String type;
    private JSONObject productConfig;
    private boolean upgradeFail = true;
    private String fileName;
    private String odlVersionNumber = "";

    @Override
    public void onCreate() {
        binding = FirmwareupgradeActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtils.i("FirmwareUpgradeActivity------onStart");
        initData();
    }

    private void initData() {
        productConfig = AppContext.getConfig();
        // 根据pid判断机器型号，进行分类显示
        robot = AppContext.get().getCurrentDevice();
        // 根据pid判断机器型号，进行分类显示图片
        binding.ivFirmwareUpdateIcon.setImageResource(productConfig.optInt(ProductConfigConstants.robot_transparent_icon));
        String deviceName = robot.getName();
        binding.tvEquipmenName.setText(deviceName);
        type = getIntent().getStringExtra("type");

        if (type.equals("rigth")) {
            String compileVerions = robot.getFirmwareInfo().getCompileVerions();
            if (compileVerions.equals("") || compileVerions == null) {
                binding.tvVersions.setText("--");//徐老师说如果取不到MCU版本号就显示——
            } else {
                binding.tvVersions.setText(compileVerions);
            }
            binding.rlProgressBar.setVisibility(View.GONE);
            binding.btnVersionsUpgrade.setVisibility(View.VISIBLE);
            odlVersionNumber = compileVerions;
        } else {
            FirmwareUpdateInfo bean = robot.getFirmwareUpdateInfo();
            int updateState = bean.getState();
            String compileVersion = robot.getFirmwareInfo().getCompileVerions();
            odlVersionNumber = compileVersion;
            if (updateState == 0) {
                //没有新版本
                binding.tvVersions.setText(compileVersion);
                binding.rlProgressBar.setVisibility(View.GONE);
                binding.btnVersionsUpgrade.setVisibility(View.VISIBLE);
            } else if (updateState == 2 || updateState == 1) {
                //强制升级
                String version = bean.getVersion();
                String desc = bean.getDesc();
                binding.tvVersionsExplanation.setText(getString(R.string.MO_Update_To));
                binding.upgradeDesc.setText(desc);
                binding.tvVersions.setText(version);
                binding.btnVersionsUpgrade.setVisibility(View.GONE);
                binding.rlProgressBar.setVisibility(View.VISIBLE);
            } else if (updateState == 3) {
                //升级中
                String version = bean.getVersion();
                String desc = bean.getDesc();
                int progress = bean.getProgress();
                //LogUtils.i("升级中 -----进度 ： " + progress);
                binding.tvVersionsExplanation.setText(getString(R.string.MO_Update_To));
                binding.upgradeDesc.setText(desc);
                binding.tvVersions.setText(version);
                binding.btnVersionsUpgrade.setVisibility(View.GONE);
                binding.rlProgressBar.setVisibility(View.VISIBLE);
                if (progress > -1) {
                    binding.progressBar.setProgress(progress);
                    binding.tvProgressPercentage.setText(progress + "");
                } else {
                    int upgradeProgress = AppContext.get().getCurrentDevice().getFirmwareUpdateInfo().getProgress();
                    binding.progressBar.setProgress(upgradeProgress);
                    binding.tvProgressPercentage.setText(upgradeProgress + "");
                }
            }
        }
        binding.ivFirmwareUpgradeReturn.setOnClickListener(this);
        binding.btnVersionsUpgrade.setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_firmwareUpgradeReturn:
                Constants.click_location = "";
                Intent_utils.backIntent(this);
                break;
            case R.id.btn_VersionsUpgrade:
                LogUtils.i("开始检测 升级------");
                robot.getFirmwareInfo().getCompileVerions();

                binding.alarmLottieAnimation.setVisibility(View.VISIBLE);
                isCheck = true;
                Constants.click_location = "detect";
                // 检测新版本
                DataParam param = new DataParam();
                param.setData_type("upgrade_package");
                AppContext.getProductService().getDataList(param);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        if (event.getType() == Event.MESSAGE_TYPE_CHECK_NEW_VERSION) {
            binding.alarmLottieAnimation.setVisibility(View.GONE);
            //检测估计版本
            if (event.isResult()) {
                FirmwareUpdateInfo firmwareUpdateInfo = (FirmwareUpdateInfo) event.getContent();
                robot.getFirmwareUpdateInfo().setCheck(true);//标记
                int status = firmwareUpdateInfo.getUpgradeStatus();
                mVersions = firmwareUpdateInfo.getNewVersion();//新版本
                currentVersion = robot.getFirmwareInfo().getCompileVerions();//机器当前版本
                LogUtils.i("mVersions ------" + mVersions);
                if (odlVersionNumber.equals(mVersions)) {
                    //无新版本  手动进行版本号比较
                    binding.alarmLottieAnimation.setVisibility(View.GONE);
                    binding.btnVersionsUpgrade.setText(this.getString(R.string.MO_New_Current));
                    binding.btnVersionsUpgrade.setTextColor(getResources().getColor(R.color.textview_color3));
                    binding.btnVersionsUpgrade.setBackgroundResource(R.drawable.checked_btn_background2);
                    binding.btnVersionsUpgrade.setClickable(false);
                    robot.getFirmwareUpdateInfo().setState(0);
                    return;
                }
                int result = AppUtil.compareVersion(mVersions, currentVersion);
                if (result == 1) {
                    status = 1;
                } else if (result == 0) {
                    status = 0;
                }
                LogUtils.i("status ------" + status);
                robot.getFirmwareUpdateInfo().setState(status);

                if (!isCheck) {
                    return;
                }
                if (status == 0) {
                    //无新版本
                    binding.alarmLottieAnimation.setVisibility(View.GONE);
                    binding.btnVersionsUpgrade.setText(this.getString(R.string.MO_New_Current));
                    binding.btnVersionsUpgrade.setTextColor(getResources().getColor(R.color.textview_color3));
                    binding.btnVersionsUpgrade.setBackgroundResource(R.drawable.checked_btn_background2);
                    binding.btnVersionsUpgrade.setClickable(false);
                    robot.getFirmwareUpdateInfo().setState(0);
                } else if (status == 1) {
                    //  有新版本
                    binding.alarmLottieAnimation.setVisibility(View.GONE);
                    //currentVersion = firmwareUpdateInfo.getCurrentVersion();//就版本
                    String version = firmwareUpdateInfo.getNewVersion();
                    mVersions = version;
                    fileName = firmwareUpdateInfo.getFileName();
                    binding.tvVersions.setText(currentVersion);
                    binding.upgradeDesc.setText(firmwareUpdateInfo.getDesc());
                    LogUtils.i(isCheck + " : version ------" + version);
                    robot.getFirmwareUpdateInfo().setVersion(mVersions);
                    robot.getFirmwareUpdateInfo().setDesc(firmwareUpdateInfo.getDesc());

                    String mContent = getString(R.string.MO_Firmware_New) + "V" + version
                            + getString(R.string.MO_Firmware_New_Tip);
                    if (isCheck) {
                        isCheck = false;
                        //对话框
                        newVersionsHintDialog(FirmwareUpgradeActivity.this, mContent,
                                getString(R.string.MO_Firmware_New), getString(R.string.U_NoUpdate),
                                getString(R.string.U_Update));
                    }
                } else if (status == 2) {
                    //升级中
//                        Toast.makeText(this, getString(R.string.Please_Wait), Toast.LENGTH_LONG).show();
//                        //显示进度条
                    binding.btnVersionsUpgrade.setVisibility(View.GONE);
                    binding.rlProgressBar.setVisibility(View.VISIBLE);
                    int upgradeProgress = AppContext.get().getCurrentDevice().getFirmwareUpdateInfo().getProgress();
                    binding.progressBar.setProgress(upgradeProgress);
                    LogUtils.i("FirmwareUpgradeActivity  升级中------");
                    robot.getFirmwareUpdateInfo().setVersion(mVersions);
                    robot.getFirmwareUpdateInfo().setDesc(firmwareUpdateInfo.getDesc());
                }
            } else {
                String code = (String) event.getContent();
                LogUtils.i("FirmwareUpgradeActivity  检测 失败 ------ " + code);
                if (!TextUtils.isEmpty(code)) {
                    Toast.makeText(this, code, Toast.LENGTH_LONG).show();
                }
            }
        } else if (event.getType() == Event.MESSAGE_TYPE_DATA_FUNC) {
            try {
                String dataFunc = (String) event.getContent();
                JSONObject jsonObject = new JSONObject(dataFunc);
                if (!jsonObject.has("func")) {
                    return;
                }
                String func = jsonObject.getString("func");
                if (!func.equals("upgrade")) {
                    return;
                }
                LogUtils.i("升级进度:" + dataFunc);
                //升级进度
                binding.btnVersionsUpgrade.setVisibility(View.GONE);
                binding.rlProgressBar.setVisibility(View.VISIBLE);
                int status = jsonObject.getInt("status");
                if (status == 1) {
                    robot.getFirmwareUpdateInfo().setState(3);
                    int progress = jsonObject.getInt("progress");
                    binding.tvProgressPercentage.setText(progress + "");
                    LogUtils.i("FirmwareUpgradeActivity  progress------" + progress);
                    if (mProgress < progress) {
                        mProgress = progress;
                        AppContext.get().getCurrentDevice().getFirmwareUpdateInfo().setProgress(progress);//保存升级进度
                        binding.progressBar.setProgress(progress);
                        robot.getFirmwareUpdateInfo().setProgress(progress);
                    }
                } else if (status == 0) {
                    odlVersionNumber = mVersions;//做版本比较
                    binding.alarmLottieAnimation.setVisibility(View.GONE);
                    robot.getFirmwareUpdateInfo().setState(0);
                    //更新成功
                    AppContext.get().getCurrentDevice().getFirmwareUpdateInfo().setProgress(0);//保存升级进度
                    binding.tvVersionsExplanation.setText(getString(R.string.MO_FirmwareVersio_Current));
                    binding.btnVersionsUpgrade.setVisibility(View.VISIBLE);
                    binding.rlProgressBar.setVisibility(View.GONE);
                    binding.btnVersionsUpgrade.setText(this.getString(R.string.MO_Update_Ok));
                    binding.btnVersionsUpgrade.setEnabled(true);
                    binding.btnVersionsUpgrade.setBackgroundResource(R.drawable.checked_btn_background);
                } else {
                    //升级失败
                    binding.alarmLottieAnimation.setVisibility(View.GONE);
                    robot.getFirmwareUpdateInfo().setState(0);
                    upgradeFail = false;
                    AppContext.get().getCurrentDevice().getFirmwareUpdateInfo().setProgress(0);//保存升级进度
                    LogUtils.i("系统升级失败 ------");
                    binding.btnVersionsUpgrade.setVisibility(View.VISIBLE);
                    binding.rlProgressBar.setVisibility(View.GONE);
                    binding.btnVersionsUpgrade.setText(getString(R.string.MO_Update_No));
                    binding.btnVersionsUpgrade.setEnabled(false);
                    binding.btnVersionsUpgrade.setBackgroundResource(R.drawable.checked_btn_background3);
                    if (productConfig.optBoolean(ProductConfigConstants.firmwareUpgradeFail)) {
                        //X3S X5 有
                        upgradeFailHintDialog(FirmwareUpgradeActivity.this);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if (event.getType() == Event.MESSAGE_TYPE_SEND_UPGRADE_URL_TO_DEVICE) {
            //获取固件包url
            YuGongRespData content = (YuGongRespData) event.getContent();
            List<YuGongRespData.FileListBean> file_list = content.getFile_list();
            String url = file_list.get(0).getData_s3_url();
            DataBag dataBag = new DataBag();
            dataBag.setType(file_list.get(0).getData_name());
            dataBag.setUrl(url);
            dataBag.setVersion(mVersions);
            AppContext.getProductService().sendUpgradeUrlToDevice(dataBag);
        }
    }

    private void upgradeFailHintDialog(Context context) {
        upgradeFailDialog = new Dialog(context);
        upgradeFailDialog.setContentView(R.layout.upgrade_fail_hint_dialog);
        upgradeFailDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        upgradeFailDialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = upgradeFailDialog.findViewById(R.id.btn_outLoginConfirm);
        TextView mBtnOutLoginCancel = upgradeFailDialog.findViewById(R.id.btn_outLoginCancel);

        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                if (!productConfig.optBoolean(ProductConfigConstants.canUpgradeFirmware)) {
                    return;
                }
                upgradeFail = true;
                Constants.ITEM_POSITION = -1;
                //开始升级
                DataParam param = new DataParam();
                param.setData_type("upgrade_package");
                param.setFile_name(fileName);
                AppContext.getProductService().getData(param);

//                binding.tvVersionsExplanation.setText(getString(R.string.MO_Update_To));
//                binding.progressBar.setProgress(0);
                // AppContext.getProductService().updateFirmware();
//                binding.btnVersionsUpgrade.setVisibility(View.GONE);
//                binding.rlProgressBar.setVisibility(View.VISIBLE);
                upgradeFailDialog.dismiss();
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upgradeFailDialog.dismiss();
            }
        });
        if (!upgradeFailDialog.isShowing()) {
            upgradeFailDialog.show();
        }
    }

    /**
     * 新版本Dialog
     */
    private void newVersionsHintDialog(Context context, String content, String dialogTitle, String str1, String str2) {
        dialog = new Dialog(context);
        dialog.setContentView(R.layout.outlogin_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_outLoginConfirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_outLoginCancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogTitle);
        TextView mContent = dialog.findViewById(R.id.tv_content);
        mTvDialogTitle.setText(dialogTitle);
        mContent.setText(content);
        mBtnOutLoginCancel.setText(str1);
        mBtnOutLoginConfirm.setText(str2);
        mBtnOutLoginConfirm.setTextColor(getResources().getColor(R.color.button_color2));

        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                if (!productConfig.optBoolean(ProductConfigConstants.canUpgradeFirmware)) {
                    ToastUtil.show(FirmwareUpgradeActivity.this, getString(R.string.MO_T_Update_Err), Toast.LENGTH_SHORT);
                    return;
                }
//                Robot device = AppContext.get().getCurrentDevice();
//                if (device.getRobotStatus().getWorkState() != RobotStatus.STATE_CHARGING || device.getRobotStatus().getBattery() <= 20) {
//                    return;
//                }
                Constants.ITEM_POSITION = -1;
                //开始升级
                binding.tvVersionsExplanation.setText(getString(R.string.MO_Update_To));
                binding.tvVersions.setText(mVersions);

                DataParam param = new DataParam();
                param.setData_type("upgrade_package");
                param.setFile_name(fileName);
                AppContext.getProductService().getData(param);

                binding.btnVersionsUpgrade.setVisibility(View.GONE);
                binding.rlProgressBar.setVisibility(View.VISIBLE);
                dialog.dismiss();
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Constants.click_location = "";
            Intent_utils.backIntent(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.i("onDestroy  onDestroy ");
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}

